package com.ly.algorithm.leetcode.binarysearch;

/**
 * @Classname Problem704
 * @Description
 *
 * 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
 *
 *
 * 示例 1:
 *
 * 输入: nums = [-1,0,3,5,9,12], target = 9
 * 输出: 4
 * 解释: 9 出现在 nums 中并且下标为 4
 * 示例 2:
 *
 * 输入: nums = [-1,0,3,5,9,12], target = 2
 * 输出: -1
 * 解释: 2 不存在 nums 中因此返回 -1
 *
 * @Date 2020/12/20 15:35
 * @Author 冷心影翼
 */
public class Problem704 {

	public static void main(String[] args) {
		Solution704 solution704 = new Solution704();
		System.out.println(solution704.search(new int[]{-1, 0, 3, 5, 9, 12}, 0));
	}

}



class Solution704 {
	public int search(int[] nums, int target) {
//		return binarySearch(nums,0,nums.length,target);
		return binarySearch(nums,target);
	}


	public int binarySearch(int[] nums,int l,int r,int target) {
		int mid = (l+r)/2;
		while (l<r) {
			if(nums[mid] == target) {
				return mid;
			}
			if(target > nums[mid]) {
				return binarySearch(nums,mid+1,r,target);
			}else {
				return binarySearch(nums,l,mid,target);
			}
		}
		return -1;
	}

	public int binarySearch(int[] nums,int target) {
		int l = 0;
		int r = nums.length;
		while (l<r) {
			int mid = (l+r)/2;
			if(nums[mid] == target) {
				return mid;
			}
			if(nums[mid] < target) {
				l = mid+1;
			}else {
				r = mid;
			}
		}
		return -1;
	}
}